package fencer911;

import java.nio.ByteBuffer;
import java.util.Arrays;
/**
 * @author <a href="https://github.com/fencer911/transfer-file-by-qrcode">transfer-file-by-qrcode</a>
 * @since 2020/03
 */
public class Encoder {


	public byte[][] encode(byte[] data, int splitSize) {

		int numChunks = numberOfChunks(data.length, splitSize);
		System.out.println("numChunks:"+numChunks+",data.length:"+data.length+",splitSize="+splitSize);
		byte[][] rangeArray = new byte[numChunks][]; 
		
		for (int i = 0; i < numChunks; i++) {
			int from = i * splitSize;
			rangeArray[i] =concat2(numChunks,i,Arrays.copyOfRange(data, from, from + splitSize));
		}
		rangeArray[numChunks-1]  =concat2(numChunks,(numChunks-1),Arrays.copyOfRange(data, (numChunks - 1) * splitSize, data.length));
		
		return rangeArray;
	}

	private byte[] concat2(int total,int index,byte[] splitedArray) {
		
		ByteBuffer dbuf = ByteBuffer.allocate(8+splitedArray.length);
		
		dbuf.putInt(total);
		dbuf.putInt(index);
		dbuf.put(splitedArray);
		return dbuf.array();
	}


	private int numberOfChunks(int length, int chunkLen) {
		int n = length / chunkLen;
		if (length % chunkLen > 0) {
			n++;
		}
		return n;
	}

	public static void main(String[] args) throws Throwable {

		System.out.println("1111111111111111111111111111111".length());
		Integer ALLONE32	=0b11111111111111111111111111111111;
		Integer ALLONE32R1	=0b10110000000000000000000000000000;
		
		//取出数字的最高3位
		//if startWith ob101
		//奇偶校验
		
		System.out.println(Integer.toBinaryString(ALLONE32R1>>29));
		System.out.println((ALLONE32R1>>29));
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.SIZE);
		
		System.out.println(Integer.toBinaryString(Integer.MAX_VALUE));
		System.out.println(Integer.bitCount(Integer.MAX_VALUE));
		
		System.out.println(Integer.toBinaryString(Integer.MIN_VALUE));
		System.out.println(Integer.bitCount(Integer.MIN_VALUE));
		int splitSize = 0b101;
	
		System.out.println(Integer.toBinaryString(splitSize));
		System.out.println(Integer.lowestOneBit(9));
		int imgSize = 300;
		String level = "";
		
		byte[] data = "123456ABCDEG".getBytes();
		byte[] meta= "123.png".getBytes();
		Encoder encoder=new Encoder();
		byte[][] rangeArray=encoder.encode(data, splitSize);//encode in  QRCODE GIF FILE.
		
		byte a=100;
		System.out.println(a);
	}

}
